﻿using EasyHttp.Http;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;

namespace EasyPayDemo.WeiPay
{
    /// <summary>
    /// 主扫接口
    /// </summary>
    public class ScanPay : IFunction
    {
        public void Execute()
        {
            string orgId = WeiPayConfig.orgId;
            Random rd = new Random();
            

            string bizTsTrace = orgId.Substring(0, 4) + orgId.Substring(orgId.Length - 4) + DateTime.Now.ToString("yyyyMMddHHmmss") + ((ulong)((rd.NextDouble() * 9 + 1) * 100000)).ToString();

            //私密信息 32位
            string key= "ASDEFC" + ((ulong)((rd.NextDouble() * 9 + 1) * 1000000000)).ToString() + "frtghy" + ((ulong)((rd.NextDouble() * 9 + 1) * 1000000000)).ToString();

            Console.WriteLine(key);
            //数字信封处理
            string digital_envelope = EncryptionUtil.RsaEncrypt(key, WeiPayConfig.PublicKey, true);

            Console.WriteLine(digital_envelope);


            M_ScanPay m_ScanPay = new M_ScanPay();

            #region data 处理

            M_ScanPayData data = new M_ScanPayData();
            data.authCode = "135907471006943270";
            //data.delaySettleFlag = "1";
            //data.infoAttach = "附加参数";
            //data.investor = "a";
            data.orderInfo = "微信被扫订单10分";
            //data.orgPreferentialAmt = "1";
            //data.patnerSettleFlag = "1";
            //data.splitSettleFlag = "0";
            //data.timeoutMinutes = 60;
            data.tradeAmt = 10;

            #endregion
            m_ScanPay.data = data;

            #region sign 处理

            var propertis = typeof(M_ScanPayData).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Select(p => p.Name).ToArray();

            ArrayList keys = new ArrayList(propertis);
            keys.Sort(StringComparer.Ordinal);
            StringBuilder chkStr = new StringBuilder();

            

            foreach (string str in keys)
            {
                var value = data.GetType().GetProperty(str).GetValue(data, null);
                if (value!=null && !string.IsNullOrWhiteSpace(value.ToString()))
                {
                    chkStr.AppendFormat("{0}={1}&", str, value);
                }
                
            }
            chkStr.Remove(chkStr.Length - 1, 1);

            //string signStr=JsonConvert.SerializeObject(data, Formatting.None);
            Console.WriteLine(chkStr.ToString());

            string sign = EncryptionUtil.RSASignJavaBouncyCastle(chkStr.ToString(),WeiPayConfig.PrivateKey, "SHA256withRSA");
            #endregion

            #region appendata 处理

            M_ScanPayAppenddata appenddata = new M_ScanPayAppenddata();
            appenddata.wxGoodsTag = "ok";
            appenddata.wxLimitPay = "no_credit";

            Identity identity = new Identity();
            identity.encryptInfo = digital_envelope;
            identity.fixBuyer = "F";
            identity.minage = "18";
            identity.needCheckInfo = "F";
            identity.type = "01";

            appenddata.identity = identity;

            #endregion
            //m_ScanPay.appendData = appenddata;


            m_ScanPay.orgId = WeiPayConfig.orgId;
            //m_ScanPay.orgInfo = "selfInfo";
            m_ScanPay.orgMercode = WeiPayConfig.orgMercode;
            m_ScanPay.orgTermno = WeiPayConfig.orgTermno;
            m_ScanPay.orgTrace = bizTsTrace;
            //m_ScanPay.prodTrace = "ORG0003320210802101628980033";
            m_ScanPay.signType = "RSA2";
            m_ScanPay.sign = sign;


            #region Http请求处理
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;

            //handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
            HttpClient httpClient = new HttpClient(new EncoderDecoderConfiguration());

            //httpClient.Request.AcceptCharSet = "UTF-8";
            httpClient.Request.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
            //httpClient.Request.AcceptCharSet = "utf-8";
            var response = httpClient.Post("https://t-wapi.bhecard.com:8443/standard/scanPay", m_ScanPay, HttpContentTypes.ApplicationJson);
            var result = response.RawText;
            #endregion

            Console.WriteLine(string.Format("返回结果：[{0}]", result));


        }


        public Tuple<string,string> GetProperName<T>(T instance,Expression<Func<T, string>> expr)
        {
            MemberExpression memberExpression = expr.Body as MemberExpression;
            string propertyName = memberExpression.Member.Name;
            string attributeName = (memberExpression.Member.GetCustomAttributes(false)[0] as DescriptionAttribute).Description;
            var property = typeof(T).GetProperties().Where(l => l.Name == propertyName).First();
            //property..GetValue(instance).ToString()
            return new Tuple<string, string>(attributeName, "");
        }
    }
}
